<template>
    <el-dialog
        title="修改推荐人"
        :visible.sync="dialogVisible"
        width="500px"
        :close-on-click-modal="false"
        @closed="resetForm"
        append-to-body>
        <el-form :model="changeForm" :rules="changeRules" ref="changeFormRef" label-width="140px" size="small">
            <el-form-item label="当前用户ID">
                <el-input :value="currentUserId" disabled/>
            </el-form-item>
            <el-form-item label="当前用户名">
                <el-input :value="currentUsername" disabled/>
            </el-form-item>
            <el-form-item label="原推荐人手机号">
                <el-input :value="originalReferrerId" disabled/>
            </el-form-item>
            <el-form-item label="新推荐人手机号" prop="newReferrerId">
                <el-input v-model="changeForm.newReferrerId" placeholder="请输入新的推荐人用户手机号"></el-input>
            </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button @click="closeDialog" size="small">取消</el-button>
            <el-button type="primary" @click="submitChange" size="small">确定修改</el-button>
        </div>
    </el-dialog>
</template>
<script>
export default {
    data() {
        return {
            dialogVisible: false,
            currentUserId: null,
            currentUsername: '',
            originalReferrerId: null, // Store the original referrer ID
            changeForm: {
                newReferrerId: '', // Input for the new referrer ID
            },
            changeRules: {
                newReferrerId: [
                    {required: true, message: '请输入新的推荐人手机号', trigger: 'blur'},
                    {pattern: /^1[3-9]\d{9}$/, message: '请输入有效的11位手机号码', trigger: 'blur'}
                ]
            }
        };
    },
    methods: {
        // Method for parent component to call
        openDialog(userData) {
            // Assuming userData from the tree node contains id, username, and pid (referrer id)
            this.currentUserId = userData.id;
            this.currentUsername = userData.username;
            this.originalReferrerId = userData.pid; // Make sure 'pid' is the correct property name
            this.dialogVisible = true;
        },
        closeDialog() {
            this.dialogVisible = false;
        },
        // Reset form when dialog is closed
        resetForm() {
            this.$refs.changeFormRef?.resetFields();
            this.currentUserId = null;
            this.currentUsername = '';
            this.originalReferrerId = null;
        },
        submitChange() {
            this.$refs.changeFormRef.validate((valid) => {
                if (valid) {
                    this.$confirm(`确定要将用户 ${this.currentUsername} (ID: ${this.currentUserId}) 的推荐人修改为 手机号: ${this.changeForm.newReferrerId} 吗？`, '确认修改推荐人', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(() => {
                        // User clicked OK - Proceed with API call
                        const apiData = {
                            user_id: this.currentUserId,
                            new_pid: this.changeForm.newReferrerId
                        };

                        this.$http.post('/admin/User/changeReferrer', apiData)
                            .then(result => {
                                if (result.code === 200) {
                                    this.$message.success('推荐人修改成功!');
                                    this.$emit('change-success'); // Notify parent
                                    this.closeDialog();
                                } else {
                                    this.$message.error(result.msg || '修改失败');
                                }
                            })
                            .catch(error => {
                                console.error('Change Referrer API error:', error);
                                this.$message.error('请求失败，请稍后重试');
                            });
                    }).catch(() => {
                        this.$message({type: 'info', message: '已取消修改'});
                    });
                } else {
                    console.log('Change referrer form validation failed');
                    return false;
                }
            });
        },
    }
};
</script>
<style scoped lang="less">
.dialog-footer {
    text-align: right;
}
/deep/.el-dialog__header{
    text-align: center !important;
}
/* Add any specific styles if needed */
</style>
